package com.igbeok.miscellaneous.concurrency.briangoetz;

public class CalculatePrimes extends Thread {
	public static final int MAX_PRIMES = 1000000;
	public static final int TEN_SECONDS = 10000;

	public volatile boolean finished = false;

	public void run() {
		int primes[] = new int[MAX_PRIMES];
		int count = 0;

		for (int i = 2; i < MAX_PRIMES; i++) {
			if (finished) {
				break;
			}

			boolean prime = true;
			for (int j = 0; j < count; j++) {
				if (i % primes[j] == 0) {
					prime = false;
					break;
				}
			}

			if (prime) {
				primes[count++] = i;
				System.out.println("Found prime: " + i);
			}
		}
	}

	public static void main(String[] args) {
		CalculatePrimes calculator = new CalculatePrimes();
		calculator.start();
		try {
			//主线程休眠10秒钟
			Thread.sleep(TEN_SECONDS);
			//调用子线程的join()方法
			//calculator.join();
		} catch (InterruptedException e) {
			System.out.println("Interrupted!");
		}

		calculator.finished = true;
	}

}
